package cn.funeralobjects.upms.extension.util;

import cn.funeralobjects.upms.enums.HttpMethod;
import cn.funeralobjects.upms.enums.Protocol;
import cn.funeralobjects.upms.extension.model.HandlerMethodMapping;
import cn.funeralobjects.upms.model.Api;
import cn.funeralobjects.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.result.method.RequestMappingInfo;
import org.springframework.web.util.pattern.PathPattern;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author FuneralObjects
 * Create date: 2020/5/3 10:10 AM
 */
public class ApiRequestMappingUtils {
    public static List<Api> toHttpApi(String scope, String name, RequestMappingInfo mappingInfo) {
        List<HttpMethod> methodList = mappingInfo.getMethodsCondition().getMethods().stream().filter(Objects::nonNull).map(m -> HttpMethod.valueOf(m.name())).collect(Collectors.toList());
        List<String> patternList = mappingInfo.getPatternsCondition().getPatterns().stream().filter(Objects::nonNull).map(PathPattern::getPatternString).collect(Collectors.toList());
        return methodList.stream()
                .flatMap(method ->
                        patternList.stream().map(pattern ->
                                new Api(name, scope, Protocol.HTTP, method, pattern)
                        )
                )
                .collect(Collectors.toList());
    }

    /**
     * 默认的创建名称函数
     *
     * @param handlerMethodMapping BaseApiHandleMapping.HandlerMethodMapping 私有类型
     * @return api名称
     */
    public static String defaultCreateNameFun(HandlerMethodMapping handlerMethodMapping) {
        String methodName = handlerMethodMapping.getMethod().getMethod().getName();
        Class<?> controllerClass = handlerMethodMapping.getMethod().getBeanType();
        RequestMapping requestMapping = controllerClass.getAnnotation(RequestMapping.class);
        String name = Optional.ofNullable(requestMapping)
                .map(RequestMapping::name)
                .filter(StringUtils::notEmpty)
                .orElseGet(controllerClass::getSimpleName);
        return name + "#" + methodName;
    }
}
